<?php
/**
 * （Logic）解析已收货库存报告
 */
namespace App\Logic\Amazon\Parse;

use App\Models\Amazon\AmazonSkuName;
use App\Models\Amazon\FbaFulfillmentInventory;
use App\Util\RExcel;
class ParseFulfillmentReport
{
    /**
     * 解析FbaFulfillment
     * @param $file
     * @return int
     */
    public static function exeParse($file){
        $lines = RExcel::importFile($file);
        $i = 0;
        $count = 0;
        $head = [];
        try{
            foreach($lines as $_str){
                $str = ParseReport::getReplaceStr($_str);
                if($i == 0){
                    $head = ParseReport::getTableHeadKey($str,self::$_keys);
                    if(empty($head))return 2;
                }else{
                    $flag = self::_addFbaFulfillment($head,$str);
                    $flag && $count++;
                }
                $i++;
            }
        }catch (\Exception $e){
            report($e);
        }
        return $i==($count+1) ? 2 : 3;
    }

    private static $_keys = ['received-date', 'fnsku', 'sku', 'product-name','quantity', 'fba-shipment-id', 'fulfillment-center-id'];

    /**
     * 添加FbaFulfillment
     * @param $head
     * @param $str
     * @return bool
     */
    private static function _addFbaFulfillment($head,$str){
        if(empty($head))return true;
        if(!$str)return true;
        $temp = explode("\t",$str);
        $keys = self::$_keys;
        $flag = false;
        foreach($keys as $key){
            if(!isset($temp[$head[$key]])){
                $flag = true;
                break;
            }
        }
        if($flag)return true;
        if(!$temp[$head['sku']])return true;
        AmazonSkuName::addName($temp[$head['sku']],$temp[$head['product-name']]);
        $receivedDate = gmdate('Y-m-d H:i:s',strtotime($temp[$head['received-date']]));
        $item = [
            'received_date' => $receivedDate,
            'fnsku' => $temp[$head['fnsku']],
            'seller_sku' => $temp[$head['sku']],
            'quantity' => $temp[$head['quantity']],
            'fba_shipment_id' => $temp[$head['fba-shipment-id']],
            'fulfillment_center_id' => $temp[$head['fulfillment-center-id']],
        ];
        $count = FbaFulfillmentInventory::query()
            ->where('received_date',$receivedDate)
            ->where('seller_sku',$temp[$head['sku']])
            ->where('quantity',$temp[$head['quantity']])
            ->where('fba_shipment_id',$temp[$head['fba-shipment-id']])
            ->where('fulfillment_center_id',$temp[$head['fulfillment-center-id']])
            ->count();
        if($count > 0)return true;
        $re = FbaFulfillmentInventory::query()->create($item);
        return !$re ? false : true;
    }
}
